import os

from django.db.models import Q
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404, JsonResponse

from script.qn import sto
from .models import Student, Grade
from dj14.settings import BASE_DIR
from dj14 import settings


# Create your views here.

def dome(request):
    # return HttpResponse('hello world')
    return redirect('crm:index')

def student(request):

    section = '学生信息'
    sts = Student.objects.all()
    search = request.GET.get('search')
    if search:
        if search.isdigit():
            sts = Student.objects.filter(Q(qq=search)|Q(phone=section),is_delete=False)
        else:
            sts = Student.objects.filter(name=search, is_delete=False)
    else:
        sts = Student.objects.filter(is_delete=False)
    sts = sts.order_by('-id')
    return render(request,'crm/student.html',context=locals())
    # return render(request, 'crm/student.html')

def student_detail(request,s_id):
    section = '学生详情页面'
    stu = Student.objects.filter(id=s_id).first()
    if not stu:
        return Http404('PAGE NOT FOUND')
    # grade = Grade.objects.all()
    return render(request,'crm/student_detail.html',locals())

def student_add(request):
    section = '学生信息添加'
    # grade = Grade.objects.all()
    if request.method == 'GET':
        return render(request,'crm/student_detail.html',locals())
    if request.method == 'POST':
        data = {
            'name':request.POST.get('name'),
            'age':request.POST.get('age'),
            'sex':request.POST.get('sex'),
            'qq':request.POST.get('qq'),
            'phone':request.POST.get('phone'),
            # 'c_time':request.POST.get('c_time'),
            'image_url': request.POST.get('image_url'),
            'g_id':int(request.POST.get('grade')),
        }
        print(data)
        Student.objects.create(**data)
        return redirect('crm:index')

def student_delete(request,s_id):
    stu = Student.objects.filter(id=s_id).first()
    if not stu:
        raise Http404('PAGE NOT FOUND')
    stu.is_delete = True
    stu.save()
    return redirect('crm:index')

def student_edit(request,s_id):

    section = '学生详情修改'
    if request.method == 'GET':
        stu = Student.objects.filter(id=s_id).first()
        if not stu:
            return Http404('PAGE NOT FOUND')
        # grade = Grade.objects.all()
        return render(request, 'crm/student_detail.html', locals())
    if request.method == 'POST':
        data = {
            'name':request.POST.get('name'),
            'age':request.POST.get('age'),
            'sex':request.POST.get('sex'),
            'qq':request.POST.get('qq'),
            'phone':request.POST.get('phone'),
            'image_url':request.POST.get('image_url'),
            'g_id':int(request.POST.get('grade')),
        }
        print(data)
        # Student.objects.create(**data)
        # return redirect('crm:stu')
        stu = Student.objects.filter(id=s_id).first()
        if not stu:
            raise Http404('PAGE NOT FOUND')
        stu.name = data['name']
        stu.age = data['age']
        stu.sex = data['sex']
        stu.qq = data['qq']
        stu.phone = data['phone']
        stu.image_url = data['image_url']
        stu.g_id = data['g_id']




        stu.save()
        return redirect('crm:index')

def up_image(request):
    if request.method == 'GET':
        raise Http404('PAGE NOT FOUND')
    if request.method == 'POST':
        file = request.FILES.get('image_url')
        print(file)
        image_url = sto(file.read())
        data = {
            'image_url':image_url
        }
        return JsonResponse(data=data)



from alipay import AliPay
import time
app_key_string=open(os.path.join(BASE_DIR, 'script', 'app_private_key.pem')).read()
alipay_key_string=open(os.path.join(BASE_DIR, 'script', 'alipay_public_key.pem')).read()

def ali_pay(request):
    alipay = AliPay(
        appid=settings.ALIPAY_APPID,
        app_notify_url = settings.ALIPAY_URL,
        app_private_key_string = app_key_string,
        alipay_public_key_string= alipay_key_string,
        sign_type = 'RSA2',
        debug = settings.ALIPAY_DEBUG,
    )

    # pc支付，需跳转
    res = alipay.api_alipay_trade_page_pay(
        subject = '支付宝测试订单，请用沙箱账号支付！',
        out_trade_no = str(int(time.time()*1000)),
        total_amount = 100,
        return_url='http://106.13.210.150:8000/aliinfo',
    )
    # 拼接url
    alipay_url = settings.ALIPAY_URL + res
    return redirect(alipay_url)

def ali_pay_info(request):
    '''
    # &out_trade_no=1582213409.4270513 # 订单号
    # &method=alipay.trade.page.pay.return
    # &total_amount=100.00  # 订单金额
    # &sign=HEhX38Q1wGttAvqMAVbAlkTgAwdAh%2F8TGd2Kyum0bHkWFSFTstAHnQx9PI0a2IQWs3wWLZNR37w1Xam1uJp8KsAVLI4q%2BHnwKs1PQZDhBPZ3SfT%2BrmaIbuyhJov68lKHODulILhUwIwnYUfejOZotFLebb%2BbMCfTm6cQDGGoQ0zPSwA%2F2q19TaTlDNdUty%2FeYuK0wcQVwDshXbjSgY2nvAaSHV9O36ysxv3uDc9XeNtDBUgxMdReQJw%2BAg8u1pRloWUL8SpccVLiW41MFpgP9ypHPIHbNSf70YEaIXs3shAoATym5nA1OFHK%2BKzqnCnvsM6vCjLvyaKXd5AO9XtfHw%3D%3D
    # &trade_no=2020022022001425201000033036  # 交易号
    # &auth_app_id=2016102100730865  # APPID
    # &version=1.0  # 版本
    # &     app_id=2016102100730865  # APPID
    # &sign_type=RSA2  #  加密方式
    # &seller_id=2088102180494100  # 商家ID
    # &timestamp=2020-02-20+23%3A44%3A24  # 交易时间
    '''

    out_trade_no = request.GET.get('out_trade_no')  # 订单号
    total_amount = request.GET.get('total_amount')  # 订单金额
    trade_no = request.GET.get('trade_no')  # 交易号
    seller_id = request.GET.get('seller_id')  # 商家ID
    timestamp = request.GET.get('timestamp')  # 交易时间

    html = '''
    <h1>交易完成</h1>
    商品订单号：{}<br>
    交易金额：{}<br>
    支付宝订单号：{}<br>
    商家ID：{}<br>
    交易时间：{}<br>
    '''.format(out_trade_no,total_amount,trade_no,seller_id,timestamp)

    return HttpResponse(html)